import axios from 'axios'
import store from '../store'

/**
 * 创建 axios 实例
 */
const service = axios.create({
  baseURL: 'http://quanzhan.site:5945/api/v1/admin', 
  timeout: 10000, 
})

/**
 * 请求拦截
 */
service.interceptors.request.use(config => {
  const token = store.getters.token
  if (token) {
    config.headers.Authorization = 'Bearer ' + token
  }

  return config
}, error => {
  return Promise.reject(error)
})

service.interceptors.response.use(response => {

  if (response.status === 200) {
    const {code, data, message} = response.data
    if (code === 200) {
      return data
    }

    // if (code === 400) {
    //   store.commit('reset')
    //   window.location.href = '/login'
    // }

    const error = new Error(message)
    return Promise.reject(error)
  }

  const err = new Error('网络请求异常...')
  return Promise.reject(err)
}, error => {
  return Promise.reject(error)
})

export default service